import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../models/device.dart';
import '../../providers/auth_provider.dart';
import '../../providers/device_provider.dart';

class DeviceDetailScreen extends StatefulWidget {
  final Device device;

  const DeviceDetailScreen({
    Key? key,
    required this.device,
  }) : super(key: key);

  @override
  State<DeviceDetailScreen> createState() => _DeviceDetailScreenState();
}

class _DeviceDetailScreenState extends State<DeviceDetailScreen> {
  late Device _device;

  @override
  void initState() {
    super.initState();
    _device = widget.device;
  }

  void _handleToggleStatus(bool status) {
    final authProvider = Provider.of<AuthProvider>(context, listen: false);
    final deviceProvider = Provider.of<DeviceProvider>(context, listen: false);
    
    if (authProvider.user != null) {
      deviceProvider.toggleDeviceStatus(authProvider.user!, _device.id, status);
      setState(() {
        _device = _device.copyWith(status: status);
      });
    }
  }

  void _handleUpdateAttributes(Map<String, dynamic> attributes) {
    final authProvider = Provider.of<AuthProvider>(context, listen: false);
    final deviceProvider = Provider.of<DeviceProvider>(context, listen: false);
    
    if (authProvider.user != null) {
      deviceProvider.updateDeviceAttributes(authProvider.user!, _device.id, attributes);
      
      final updatedAttributes = Map<String, dynamic>.from(_device.attributes);
      updatedAttributes.addAll(attributes);
      
      setState(() {
        _device = _device.copyWith(attributes: updatedAttributes);
      });
    }
  }

  Widget _buildDeviceControls() {
    switch (_device.type) {
      case 'light':
        return _buildLightControls();
      case 'thermostat':
        return _buildThermostatControls();
      case 'lock':
        return _buildLockControls();
      case 'camera':
        return _buildCameraControls();
      case 'speaker':
        return _buildSpeakerControls();
      default:
        return _buildGenericControls();
    }
  }

  Widget _buildLightControls() {
    final brightness = _device.attributes['brightness'] as int? ?? 100;
    
    return Column(
      children: [
        SwitchListTile(
          title: const Text('开关状态'),
          value: _device.status,
          onChanged: _handleToggleStatus,
        ),
        const Divider(),
        ListTile(
          title: const Text('亮度'),
          subtitle: Slider(
            value: brightness.toDouble(),
            min: 0,
            max: 100,
            divisions: 10,
            label: '$brightness%',
            onChanged: _device.status
                ? (value) {
                    _handleUpdateAttributes({'brightness': value.round()});
                  }
                : null,
          ),
        ),
      ],
    );
  }

  Widget _buildThermostatControls() {
    final temperature = _device.attributes['temperature'] as double? ?? 22.0;
    
    return Column(
      children: [
        SwitchListTile(
          title: const Text('开关状态'),
          value: _device.status,
          onChanged: _handleToggleStatus,
        ),
        const Divider(),
        ListTile(
          title: const Text('温度设置'),
          subtitle: Slider(
            value: temperature,
            min: 16,
            max: 30,
            divisions: 14,
            label: '${temperature.toStringAsFixed(1)}°C',
            onChanged: _device.status
                ? (value) {
                    _handleUpdateAttributes({'temperature': double.parse(value.toStringAsFixed(1))});
                  }
                : null,
          ),
        ),
      ],
    );
  }

  Widget _buildLockControls() {
    return Column(
      children: [
        ListTile(
          title: Text(_device.status ? '已锁定' : '已解锁'),
          trailing: ElevatedButton(
            onPressed: () => _handleToggleStatus(!_device.status),
            child: Text(_device.status ? '解锁' : '锁定'),
          ),
        ),
      ],
    );
  }

  Widget _buildCameraControls() {
    return Column(
      children: [
        SwitchListTile(
          title: const Text('摄像头状态'),
          value: _device.status,
          onChanged: _handleToggleStatus,
        ),
        const Divider(),
        if (_device.status)
          const Center(
            child: Padding(
              padding: EdgeInsets.all(16.0),
              child: Text('摄像头画面将在后续版本中实现'),
            ),
          ),
      ],
    );
  }

  Widget _buildSpeakerControls() {
    final volume = _device.attributes['volume'] as int? ?? 50;
    
    return Column(
      children: [
        SwitchListTile(
          title: const Text('扬声器状态'),
          value: _device.status,
          onChanged: _handleToggleStatus,
        ),
        const Divider(),
        ListTile(
          title: const Text('音量'),
          subtitle: Slider(
            value: volume.toDouble(),
            min: 0,
            max: 100,
            divisions: 10,
            label: '$volume%',
            onChanged: _device.status
                ? (value) {
                    _handleUpdateAttributes({'volume': value.round()});
                  }
                : null,
          ),
        ),
      ],
    );
  }

  Widget _buildGenericControls() {
    return SwitchListTile(
      title: const Text('设备状态'),
      value: _device.status,
      onChanged: _handleToggleStatus,
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(_device.name),
      ),
      body: ListView(
        children: [
          Padding(
            padding: const EdgeInsets.all(16.0),
            child: Row(
              children: [
                Icon(
                  _getDeviceIcon(),
                  size: 48.0,
                  color: _device.status ? Colors.blue : Colors.grey,
                ),
                const SizedBox(width: 16.0),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        _device.name,
                        style: const TextStyle(
                          fontSize: 24.0,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                      Text(
                        '类型: ${_getDeviceTypeName()}',
                        style: const TextStyle(
                          fontSize: 16.0,
                          color: Colors.grey,
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
          const Divider(),
          _buildDeviceControls(),
          const Divider(),
          ListTile(
            title: const Text('设备ID'),
            subtitle: Text(_device.id),
          ),
        ],
      ),
    );
  }

  IconData _getDeviceIcon() {
    switch (_device.type) {
      case 'light':
        return Icons.lightbulb;
      case 'thermostat':
        return Icons.thermostat;
      case 'lock':
        return Icons.lock;
      case 'camera':
        return Icons.videocam;
      case 'speaker':
        return Icons.speaker;
      default:
        return Icons.devices_other;
    }
  }

  String _getDeviceTypeName() {
    switch (_device.type) {
      case 'light':
        return '智能灯';
      case 'thermostat':
        return '温控器';
      case 'lock':
        return '智能锁';
      case 'camera':
        return '摄像头';
      case 'speaker':
        return '智能音箱';
      default:
        return '其他设备';
    }
  }
}